// pages/cansai/cansai.js
Page({

  tijiao() {
    var that = this;
    var matchid = this.data.matchid;
    var index = this.data.category + '';
    var userid = this.data.userid;
    var username = this.data.username;
    var time = new Date();
    var image = null;
    wx.chooseMedia({
      count: 1,
      success(res) {
        console.log(res.tempFiles)
        var po = res.tempFiles[0].tempFilePath.lastIndexOf(".")
        var ext = res.tempFiles[0].tempFilePath.slice(po)
        wx.cloud.uploadFile({
          cloudPath: userid + new Date().getTime() + ext,
          filePath: res.tempFiles[0].tempFilePath,
          success(res) {
            console.log(res.fileID);
            image = res.fileID;
            that.setData({
              currentImage: image
            });
            var database = wx.cloud.database();
            var data = {
              matchid: matchid,
              index: index,
              userid: userid,
              username: username,
              time: time,
              image: image
            }
            database.collection("tb_item").add({
              data
            }).then((s) => {
              if (s) wx.showToast({
                title: '提交图片成功',
              })
              /*判断是否已经完成比赛*/
              database.collection("tb_item").where({
                matchid:that.data.matchid,
                userid:that.data.userid
              }).get().then((res)=>{
                if(res){
                  if(res.data.length == that.data.picnames.length){
                    wx.showToast({
                      title: '已经完成比赛',
                    })
                    /*记录个人成绩*/
                    var data2 = {
                      userid:that.data.userid,
                      matchid:that.data.matchid,
                      username: that.data.username,
                      time:new Date(),
                      haoshi:null,
                      mingci:null
                    }
                    /*查询用户到达第一个场景的时间*/
                    database.collection("tb_item").where({
                      matchid:that.data.matchid,
                      userid:that.data.userid
                    }).get().then((res)=>{
                      if(res){
                        var min = data2.time.getTime();
                        for(let i=0;i<res.data.length;i++){
                          if(res.data[i].time.getTime()<min){
                            min =res.data[i].time.getTime();
                          }
                        }
                        /*获取当前用户完成比赛的时间间隔时间*/
                        var jiange = data2.time.getTime()-min;
                        /*将间隔时间进行拆解，变成小时，分钟，秒钟*/
                        var h = Math.round(jiange/(1000*60*60));
                        var m =  Math.round(jiange%(1000*60*60)/(1000*60));
                        var s = Math.round(jiange%(1000*60)/1000);
                        data2.haoshi = h+"小时"+m+"分钟"+s+"秒钟";
                        /*确定当时选手的比赛名次*/
                        database.collection('tb_score_p').where({
                          matchid:that.data.matchid
                        }).get().then((res)=>{
                          if(res){
                            data2.mingci = res.data.length+1;
                          }else{
                            data2.mingci = 1;
                          }
                          /*把当前用户的成绩写入数据库*/
                          database.collection('tb_score_p').add({
                            data:data2
                          }).then((res)=>{
                            if(res){
                              wx.showToast({
                                title: '成绩记录成功',
                              })
                              /*插入团队成绩记录*/
                              database.collection('tb_rudui').where({userid:that.data.userid}).get().then((res)=>{
                                if(res){
                                  var groupid = res.data[0].groupid;
                                  /*将当前用户加入完赛记录表，然后数完记录表中当前团队的人数。如果等于该团队的总人数，则完赛*/
                                  var data = {
                                    matchid:that.data.matchid,
                                    userid:that.data.userid,
                                    groupid:groupid
                                  }
                                  database.collection("tb_wansai").add({data:data}).then((res)=>{
                                    if(res){
                                      /*数当前团队完赛的记录有多少条*/
                                      database.collection("tb_wansai").where({matchid:that.data.matchid,groupid:groupid}).get().then((res2)=>{
                                        if(res2){
                                          database.collection("tb_group").where({_id:groupid}).get().then((res3)=>{
                                            if(res3){
                                              if(res2.data.length == res3.data[0].groupnum){
                                                wx.showToast({
                                                  title: '该团队已完赛',
                                                })
                                                /*创建团队完赛记录*/
                                                var data2 = {
                                                  groupid:groupid,
                                                  groupname:null,
                                                  matchid:that.data.matchid,
                                                  matchname:that.data.matchname,
                                                  mingci:null,
                                                  time:new Date()
                                                  /*写到这里*/
                                                  

                                                }
                                                database.collection("tb_score_g").where({matchid:that.data.matchid}).get().then((res)=>{
                                                  if(res){
                                                    data2.mingci = res.data.length+1;
                                                  }
                                                  else{
                                                    data2.mingci = 1;
                                                  }
                                                  /*小组名字*/
                                                  database.collection("tb_group").where({_id:groupid}).get().then((res)=>{
                                                    if(res){
                                                      data2.groupname = res.data[0].groupname;
                                                      database.collection("tb_score_g").add({data:data2}).then((res)=>{
                                                        if(res){
                                                          wx.showToast({
                                                            title: '小组完成比赛',
                                                          })
                                                        }
                                                      })
                                                    }
                                                  })
                                                  /*小组成绩录入数据库*/
                                                  
                                                })
                                              }

                                            }
                                          })
                                        }
                                      })
                                    }
                                  })
                                }
                              })
                            }
                          })
                        });
                      }
                    })
                  }
                }
              });
              that.setData({
                isDisabled:true
              })



              var time2 = data.time;
              var d = time2.toLocaleDateString().substring(0, 10);
              var t = time2.toTimeString().substring(0, 8);
              time2 = d + " " + t;
              data.time = time2;
              that.data.xuanshou.push(data);
              that.setData({
                xuanshou: that.data.xuanshou
              });

            })
          }
        })
      }
    })
  },

  click: function (e) {

    this.setData({
      category: e.currentTarget.id + ""
    });
    var that = this;
    var database = wx.cloud.database();
    database.collection("tb_item").where({
      matchid: that.data.matchid,
      index: that.data.category + ""
    }).get().then((res) => {
      that.setData({
        xuanshou: res.data
      });
      that.setData({
        isDisabled:false
      })
      for (let i = 0; i < that.data.xuanshou.length; i++) {
        var time = that.data.xuanshou[i].time;
        var d = time.toLocaleDateString().substring(0, 10);
        var t = time.toTimeString().substring(0, 8);
        time = d + " " + t;
        that.data.xuanshou[i].time = time;
        if(that.data.xuanshou[i].userid == that.data.userid){
          that.setData({
            isDisabled:true
          })
        }
      }
      that.setData({
        xuanshou: that.data.xuanshou
      });

    })
  },
  dianji() {
    this.setData({
      dialogShow_match: true,
      currentImage: this.data.picurls[this.data.category]
    })

  },
  /**
   * 页面的初始数据
   */
  data: {
    matchid: null,
    match: null,
    picnames: [],
    category: 0,
    picurls: [],
    index: 0,
    dialogShow_match: false,
    currentImage: null,
    userid: null,
    username: null,
    xuanshou: [],
    isDisabled:false

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    wx.getStorage({
      key: "matchid",
      success(res) {
        console.log('storage数据:' + res.data);
        that.data.matchid = res.data;
        that.setData({
          matchid: that.data.matchid
        });
        console.log('match_id:' + that.data.matchid);
        var database = wx.cloud.database();
        database.collection("tb_match").where({
          _id: that.data.matchid
        }).get().then((res) => {
          if (res.data.length > 0) {
            that.setData({
              match: res.data[0]
            });
            var picnames = [];
            var match = that.data.match;
            var picurls = [];
            for (let i = 0; i < match.imageList.length; i++) {
              var data = match.imageList[i];
              picurls.push('' + data);
              var loc = data.lastIndexOf("/");
              data = data.slice(loc + 1);
              loc = data.lastIndexOf("_");
              data = data.slice(0, loc);
              picnames.push(data);
            }
            that.setData({
              picnames: picnames,
              picurls: picurls
            });
          }
        });
      }
    });
    wx.getStorage({
      key: "userid",
      success(res) {
        that.setData({
          userid: res.data
        });
        //到数据库里面找到当前用户参加的比赛
        var database = wx.cloud.database();
        database.collection("tb_user").where({
          _id: that.data.userid
        }).get().then((r) => {
          that.setData({
            username: r.data[0].name
          });
        })
      }
    })

    var database = wx.cloud.database();
    database.collection('tb_item').where({
      matchid: that.data.matchid,
      index: 0 + ""
    }).get().then((g) => {
      that.setData({
        xuanshou: g.data
      });


    })


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    var database = wx.cloud.database();
    var that = this;
    database.collection('tb_item').where({
      matchid: that.data.matchid,
      index: 0 + ""
    }).get().then((g) => {
      that.setData({
        xuanshou: g.data
      });
      for (let i = 0; i < that.data.xuanshou.length; i++) {
        var time = that.data.xuanshou[i].time;
        var d = time.toLocaleDateString().substring(0, 10);
        var t = time.toTimeString().substring(0, 8);
        time = d + " " + t;
        that.data.xuanshou[i].time = time;
        if(that.data.xuanshou[i].userid==that.data.userid){
          that.data.isDisabled = true;
          that.setData({
            isDisabled:that.data.isDisabled
          })
        }
      }
      that.setData({
        xuanshou: that.data.xuanshou
      });
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})